﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace DotNetExtensions.Core.Extensions
{
    public class FormKeyAttribute : Attribute
    {
        public string Name { get; set; }
        public FormKeyAttribute(string name)
        {
            this.Name = name;
        }
    }
    public static class IFormCollectionExtensions
    {
        public static T Parse<T>(this IFormCollection form) where T : new()
        {
            if (form == null || form.Count == 0) return default(T);

            var properties = typeof(T).GetProperties();

            T data = new T();

            foreach (var item in properties)
            {
                string key = item.Name;
                var formKey = item.GetCustomAttribute<FormKeyAttribute>();
                if (formKey != null && !string.IsNullOrEmpty(formKey.Name)) key = formKey.Name;

                foreach (var k in form.Keys)
                {
                    if (k.ToLower() == key.ToLower())
                    {
                        StringValues values = form[k];
                        if (values.Count == 0) continue;
                        if (values.Count > 1 && item.PropertyType is ICollection)
                        {
                            values.ToArray();
                            item.SetValue(data, values.ToArray());
                        }
                        else
                        {
                            item.SetValue(data, form[k].ToString());
                        }
                    }
                }
            }

            return data;
        }

        public static bool TryParse<T>(this IFormCollection form, out T data) where T : new()
        {
            data = form.Parse<T>();
            return data != null;
        }
    }
}
